<template>
  <div class="container">
    <header class="select_header">
      <span >选择一个文件夹:</span>
     
     <input  class="path_input" v-model="basePath" />
     <img src="/images/user/setting.svg" @click="showUserDialog" class="user_btn" />
      <button class="init_btn" @click="initDir">初始化</button>
    </header>

    <div class="container_mes_box" :key="chatInitKey">
      <template v-for="(item, index) in fileListArr" :key="index">
      
        <div class="current_mes_box" v-if="currentUserId === item.user_id">
  <time class="title_time">{{ item.time }}</time>
  <div class="currnet_mes_flex">
   

        <img
        class="avatar"
          :src="user_Avatars.value[item.user_id].url"
          :alt="user_Avatars.value[item.user_id].name"
        />
        <div class="bubble"  v-if="item.mes_type === 'image'">
        <img
        style="width: 50px;height: 50px;"
          @copy="handleCopy"
          @click="imgView(imageBaseList.list[item.name])"
          class="image-content"
          :src="imageBaseList.list[item.name]"
          :alt="item.name"
        />
        <text class="delete_btn" @click="deleteIn(item)">删除</text>
        </div>
        <div class="bubble" v-else>
         
          <text class="text-content" 
          style=" background-color:#409eff ; border-radius: 15px 0px 15px 15px;"
          >{{ item.contect }}</text>
          <text class="delete_btn" @click="deleteIn(item)">删除</text>
        </div>

      </div>
      </div>   

        <!-- 左侧 -->
      <div v-else class="other_mes_box">
        <time class="title_time">{{ item.time }}</time>
  
        <img
        class="avatar"
        style="margin-top: 15px;"
          :src="user_Avatars.value[item.user_id].url"
          :alt="user_Avatars.value[item.user_id].name"
        />
        <div class="bubble"  v-if="item.mes_type === 'image'">
          <span class="user_name_text">{{user_Avatars.value[item.user_id].name}}</span>
        <img
        style="width: 50px;height: 50px;margin-left: 15px;margin-top: 15px;"
          @copy="handleCopy"
             @click="imgView(imageBaseList.list[item.name])"
          class="image-content"
          :src="imageBaseList.list[item.name]"
          alt="item.name"
        />
        <text class="delete_btn" @click="deleteIn(item)">删除</text>
        </div>
        <div class="bubble" v-else>
          <span class="user_name_text">{{user_Avatars.value[item.user_id].name}}</span>
          <text class="text-content" style="margin-left: 15px;margin-top: 15px;" >{{ item.contect }}</text>
          <text class="delete_btn" @click="deleteIn(item)">删除</text>
        </div>
      </div>
 <!-- 右侧 -->

      </template>

    </div>

    <div class="console_box">
      <div class="console_nav">
        <button>+</button>
        <button>文件</button>
        <button>占位</button>
        <MySelect
        style="vertical-align: bottom;"
        v-model:currentUserId="currentUserId"
        :options="user_Avatars.list"

       :selectConfig = "{label:'user_name',id:'user_id'}"
        >
        <template #option="{ option }">
          <img
        style="width: 20px;height: 20px;"
          :src="option.url"
         
        />
           <span>{{ option.user_name }}</span> 
      
      
    
      </template>
      </MySelect>
      </div>

      <textarea
        v-model="textareaValue"
        placeholder="请输入内容"
        id="richText"
        rows="10"
        cols="50"
        @paste="textPaste"
      >
      </textarea>

      <button class="enter_btn" @click="send">发送</button>
    </div>
    <AvatarDialog
    :basePath="basePath"
    v-if="userConfigList.visible"
     v-model:visible="userConfigList.visible"
     :userList="userConfigList.data"
    />
   <MyDialog
      v-if="showImgConfig.visible"
      v-model="showImgConfig.visible"
      title="圖片展示"
      @confirm="imgShowConfirm"
      @cancel="imgShowConfirm"
    >
      <div class="dialog_body" >
        <ImgShow
              :src="showImgConfig.imgSrc"
        />

      </div>

    </MyDialog>
  </div>
</template>

<script setup>
// const { proxy } = getCurrentInstance();
import { onMounted, reactive, ref } from "vue";
import { invoke } from "@tauri-apps/api/core";
import MySelect from "@/components/Select.vue"
import AvatarDialog from "./avatar/list.vue"
import { convertToBase64 } from "@/tool/tool.js";
import MyDialog from "@/components/Dialog.vue";
import ImgShow from "./imgScoped/imgContent.vue"
const fileListArr = ref([]);
const imageBaseList = reactive({list:{}})
const chatInitKey = ref(true)
const textareaValue = ref("");
const basePath = ref('C:/Users/Admin/Desktop/aa')
const currentUserId = ref("user_01")
const user_Avatars = reactive({
  value:{},
  list:[
  {  user_name:"dd",url:"",user_id:'dd'},
  {  user_name:"ddc",url:"",user_id:'ddc'},
  ]
})
const userConfigList = reactive({
  visible:false,
  data:[]
})
const showImgConfig = reactive({
  visible:false,
  imgSrc:""
})
//页面
//存入当前current
onMounted(()=>{

  // basePath.value  = 'C:/Users/libai/Desktop/文件加'
})
function imgView(e){

    showImgConfig.imgSrc = e
    showImgConfig.visible = true
  console.log(showImgConfig.visible)
}
function imgShowConfirm(){
showImgConfig.imgSrc = ''
  showImgConfig.visible = false
}
function showUserDialog(params) {
  
  userConfigList.data = user_Avatars.list
  userConfigList.visible = true
}

function initDir(params) {
  invoke("initlist", {
    path: basePath.value,
  }).then((res) => {

    if(res&&res.log){
      //处理文件log消息与消息图片
 fileListArr.value = res.log
 console.log(res)
 imageBaseList.list ={}
 fileListArr.value.forEach((item)=>{
  if(item.mes_type==='image'){
    let imgIndex = res.images.findIndex((imgItem)=>imgItem.name ===item.name)
    if(imgIndex!==-1){
      imageBaseList.list[item.name] = item.base64_header +',' + res.images[imgIndex].url
    }
  }
 })
 chatInitKey.value = !chatInitKey.value
//处理头像
user_Avatars.value = {}
user_Avatars.list = []
res.user.forEach((item,index)=>{
  let imgValueIndex = res.userImages.findIndex((imgItem)=>imgItem.name == item.name)
  let imgValue = imgValueIndex===-1?{}:res.userImages[imgValueIndex]

  user_Avatars.value[item.user_id] = {
    name:item.user_name,
    url :imgValue.base64_header + imgValue.url
  }
  item.url =imgValue.base64_header + imgValue.url 
  user_Avatars.list.push(item)
})
//处理默认登陆
currentUserId.value = user_Avatars.list[0].user_id

    }
    else{

    }
  })
}
async function textPaste(e) {
  const file = Array.from(e.clipboardData.items)
    .find(v => v.type.includes('image'))
    ?.getAsFile()
   if(!file){
return
   }

  let base64Str = await  convertToBase64(file)

  const [prefix, data] = base64Str.split(',');
  let obj = {
    time:new Date(),
    mes_type:'image',
    imgtype: 'jpeg',
    base64_header:prefix,
    url: data,
    user_id:currentUserId.value,
    name: `${new Date().getTime()}_name`, 
  }

  invoke("addMes",{
      path: basePath.value,
      jsonData: JSON.stringify(obj),
    }).then((res) => {

    if(res==='OK'){
      textareaValue.value = ''
      refresh(obj,'add')
    }else{

    }
  })

}


function refresh(row,type) {
if(type==='delete'){
let index = fileListArr.value.findIndex((item)=>item.name === row.name)
if(index===-1){
  alert("前端删除失败")
}else{
  if(row.mes_type == 'image'){
  delete  imageBaseList.list[row.name]
  }
  fileListArr.value.splice(index,1)
  
}
}else{
  fileListArr.value.push(row)
  if(row.mes_type == 'image'){
    imageBaseList.list[row.name] = row.base64_header +','+ row.url
  }
}
}

function deleteIn(row,index) {
  
  invoke("deleteMes",{
      path: basePath.value,
      jsonData: JSON.stringify(row),
    }).then((res) => {
 
    if(res==='OK'){
      refresh(row,'delete')
    }else{

    }
  })
  

}
//去掉删除的
function deleteRow(params) {
  fileListArr.value.splice(params,1)
}
function addRow(params) {
  fileListArr.value.push(params)
}
function send(params) {
  let value = textareaValue.value
  let obj = {
    time:new Date(),
    contect:value,
    type:'txt',
    user_id:currentUserId.value,
     url: params,
     name: `${new Date().getTime()}_name`, 
  }

  invoke("addMes",{
      path: basePath.value,
      jsonData: JSON.stringify(obj),
    }).then((res) => {

    if(res==='OK'){
      refresh(obj,'add')
      textareaValue.value = ''
    }else{

    }
  })
}

const handleCopy = async (e) => {
  try {
    const img = e.target;
    // 通过 Canvas 获取图片 Blob
    const blob = await getImageBlob(img);
    // 写入剪贴板
    await navigator.clipboard.write([
      new ClipboardItem({ [blob.type]: blob })
    ]);
    console.log('图片已复制到剪贴板');
  } catch (error) {
    console.error('复制失败:', error);
  }
};

const getImageBlob = (img) => {
  return new Promise((resolve, reject) => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = img.naturalWidth;
    canvas.height = img.naturalHeight;
    ctx.drawImage(img, 0, 0);
    // 将 Canvas 转为 Blob
    canvas.toBlob((blob) => {
      blob ? resolve(blob) : reject('转换失败');
    });
  });
};
</script>

<style scoped>

.container {
  max-width: 800px;
  width: calc(100% - 40px);
  padding-left: 40px;
  height: 100%;
  background-color: #f5f5f5;
}
.select_header {
  text-align: left;
  /* padding-left: 10px; */
  height: 50px;
  display: flex;
 position: relative;
  align-items: center;
  width: 100%;
}
.path_input{
  width: 50%;
  margin-left: 20px;
}
.init_btn{

height: 40px;
padding: 5px;
line-height: 30px;
text-align: center;
margin-right:20px ;
position: absolute;
right: 20px;
}
.container_mes_box {
  height: calc(100% - 192px);
  width: calc(100% - 2px);

  overflow: auto;
  /* background-color: aquamarine; */
  border: solid 1px #ececec;
}

.console_box {
  width: 100%;
  margin: auto;
  /* background-color: #ddd; */
  height: 139px;
  position: relative;
  border-top: solid 1px #ececec;
}

.file-item {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ddd;
}
.bubble_box{

}
.bubble{
  /* background-color: aqua; */
  width: calc(100% - 60px);
  margin-top: 15px;
  display: inline-flex;
  position: relative;
}
.user_name_text{
  position: absolute;
  top: -10px;
  color: #b8b8b8;
}
.title_time{
  display: block;
  background-color: #dadada;
  color: #fff;
  /* border-radius: 50%; */
  text-align: center;
}
 .avatar{
  margin-top: 0px;
  vertical-align: top;
  display: inline-block;
  border-radius: 50%;
  height: 40px;
  width: 40px;
  background-color: greenyellow;
  text-align: center;
  line-height: 40px;
}
.text-content {
  background: #fff;
  display: inline-block;  /* 让元素宽度包裹内容 */
  max-width: 40%;         /* 最大宽度不超过父容器40% */
  word-break: break-word; /* 允许长单词换行 */
  overflow-wrap: anywhere;/* 更智能的换行方式 */
margin-right: 5px;
min-width: 20px;
  padding: 10px 15px;
  border-radius: 0 15px 15px 15px;
  /* white-space: pre-wrap;
  display: block; */
}
.delete_btn{
  height: 20px;
  width: 25px;
  background-color: red;
  color: #ddd;
  vertical-align: bottom;
  font-size: 11px;
  line-height: 20px;
  margin-top: 25px;
}
.image-content {
  max-width: 100%;
  display: block;
}

#folderInput {
  width: 80px;
  padding: 0px;
}

.enter_btn {
  position: absolute;
  bottom: 5px;
  right: 30px;
  height: 30px;
  padding: 5px;
  border-radius: 0px;
}
.console_nav {
  text-align: left;
}
#richText {
  width: 90%;
  height: 70px;
}
.console_nav > button {
  width: 25px;
  height: 25px;
  font-size: 10px;
  padding: 0px;
  vertical-align: middle;
}
.current_mes_box{
  width: 100%;

}
.currnet_mes_flex{

  display: flex;


  flex-direction: row-reverse; 
}
.currnet_mes_flex > .bubble{
  flex-direction: row-reverse; 
}
.user_btn{
  border-radius: 50px;
  height: 40px;
  width: 40px;
  padding: 5px;
  font-size:14px;

}
</style>
<style>
.dialog_body{
width: 500px;
  height: 300px;
}
</style>